﻿using Evision.Insure;
using Evision.Zlsoft.Miaiap.Core.Model;
using Evision.Zlsoft.Miaiap.Core.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using Zlsy.Core.Data;

namespace Evision.Zlsoft.Miaiap.Core {
    [Guid("3AEA28AC-B740-466A-ABF1-62BB01D22CCE"), ClassInterface(ClassInterfaceType.AutoDual) ,ProgId("zlMIAIAP.clsMiaiap")]
    public class CallMiaiapFacade {
        private static Zlsy.Core.ILogger _logg = Zlsy.Core.Log.GetLog("MIAIAP");


        public void Init(ADODB.Connection cnOracle) {
            _logg.Info("InitOracle");
            Adodb.Init(cnOracle);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="strUserCode">工号</param>
        public void MiaiapLogin(string strUserCode) {
            try {
                string userid = Adodb.GetScalar<string>(@"Select  p.id From 人员表 P Where 编号 = ?", strUserCode);
                string userno = Adodb.GetScalar<string>(@"select 参数值 from 三方接口配置 where 接口名 = '智慧干诊' and 参数名 = '客户端地址'");
                System.Diagnostics.Process.Start(userno, userid);
            } catch (Exception e) {
                _logg.Error($"登录错误信息：{e}");
            }

        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public bool MiaiapQuit() {
            try {
                MessageBox.Show("退出调用成功");
                InputQuit inputQuit = ModelQuit.GetInputQuit();
                string url = Adodb.GetScalar<string>(@"select 参数值 from 三方接口配置 where 接口名 = '智慧干诊' and 参数名 = 'webService'");
                _logg.Info($"退出请求数据：{inputQuit}");
                requestService(8002, inputQuit, url);
            } catch (Exception e) {
                _logg.Error($"退出错误信息：{e}");
            }
            return true;
        }
        /// <summary>
        /// 处方审批
        /// </summary>
        /// <param name="patiendId">病人id</param>
        /// <param name="pageId">主页id</param>
        /// <param name="lngAdviceIDs">医嘱ids</param>
        /// <param name="strNo">挂号no</param>
        /// <param name="outorin"></param>
        /// <returns></returns>
        public bool MiaiapApproval(Int32 patiendId, string varRecId, string[] arrData, bool outorin) {
            try {
                _logg.Info($"处方审批请求数据：patiendId:{patiendId},pageId:{varRecId},arrData{arrData},outorin:{outorin}");
                InputPrescriptionApproval inputPrescriptionApproval = ModelApproval.GetMiaiapApproval(patiendId, Convert.ToInt32(varRecId), arrData, outorin);
                if (inputPrescriptionApproval != null) {
                    var serializer = new XmlSerializer(typeof(InputPrescriptionApproval));
                    //公共
                    InputPublic inputPublic = ModelPublic.GetInputPublic(inputPrescriptionApproval);
                    string baseXmlString = SerializeObjectToXml(inputPublic);
                    string detailsXmlString = SerializeObjectToXml(inputPrescriptionApproval);
                    MiAIAp.WebHelper W = new MiAIAp.WebHelper();
                    _logg.Info($"处方审批请求数据：{baseXmlString}，{detailsXmlString}");
                    int res = W.MIHandel(8003, baseXmlString, detailsXmlString);
                    if(res == 1) {
                        MessageBox.Show("该医嘱正在审批中","智慧干诊提示");
                        return false;
                    }else if(res == 2) {
                        MessageBox.Show("该医嘱审批未通过", "智慧干诊提示");
                        return false;
                    }
                    return true;
                    
                } else {
                    _logg.Info($"处方审批请求数据为空");
                    return false;
                }
            } catch (Exception e) {
                _logg.Error($"处方审批错误信息：{e}");
                return false;
            }
        }
        /// <summary>
        /// 审批状态
        /// </summary>
        /// <param name="sendNo">医嘱Id</param>
        /// <param name="No">门诊号/住院号</param>
        /// <param name="outorin">门诊住院标识</param>
        /// <returns></returns>
        public bool MiaiapApprovalStauts(Int32 sendId, Int32 patiendId, Int32 pageId, string No, bool outorin) {
            try {
                MessageBox.Show("处方状态调用成功");
                InputApprovalStatus inputApprovalStatus =ModelApprovalStatus.GetApprovalStatus(sendId, patiendId, pageId, No, outorin);
                var serializer = new XmlSerializer(typeof(InputApprovalStatus));
                // 创建一个 StringWriter 来接收序列化的 XML
                using (var stringWriter = new StringWriter()) {
                    serializer.Serialize(stringWriter, inputApprovalStatus);
                    string xmlString = stringWriter.ToString();
                    _logg.Info($"处方状态请求数据：{xmlString}");
                }
            } catch (Exception e) {
                _logg.Error($"错误信息：{e}");
            }
            return true;
        }
        //撤销审批
        public bool IsApprovalRevoked(Int32 sendId, Int32 patiendId, Int32 pageId, string No, bool outorin) {
            try {
                //MessageBox.Show("处方撤销调用成功");
                 _logg.Info($"处方撤销入参请求数据：sendId:{sendId},patiendId:{patiendId},pageId:{pageId},No:{No}");
                InputApprovalStatus inputApprovalStatus = ModelApprovalStatus.GetApprovalStatus(sendId, patiendId, pageId, No, outorin);
                var serializer = new XmlSerializer(typeof(InputApprovalStatus));
                    //公共
                    InputPublic inputPublic = ModelPublic.GetInputPublic();
                    string baseXmlString = SerializeObjectToXml(inputPublic);
                    string detailsXmlString = SerializeObjectToXml(inputApprovalStatus);
                    MiAIAp.WebHelper W = new MiAIAp.WebHelper();
                    int res =  W.MIHandel(8006, baseXmlString, detailsXmlString);
                    _logg.Info($"处方审批撤销请求数据：{baseXmlString},{detailsXmlString}");
                    if (res == -1) {
                        MessageBox.Show("撤销审批失败", "智慧干诊提示");
                        return false;
                    }
                    return true;
            } catch (Exception e) {
                _logg.Error($"处方审批撤销错误信息：{e}");
                return false;
            }
        }
        public void requestService(int code,Object inputQuit,string url) {
            // 序列化对象为XML
            string xmlString = SerializeObjectToXml(inputQuit);
            InputPublic inputPublic = ModelPublic.GetInputPublic();
            string baseXmlString = SerializeObjectToXml(inputQuit);
            // 创建 SOAP 请求
            string soapEnvelope = $@"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                           xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
                           xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                <soap:Body>
                    <MIHandel xmlns=""http://tempuri.org/"">
                        <funID>{code}</funID>
                        {baseXmlString}
                        {xmlString}
                    </MIHandel>
                </soap:Body>
            </soap:Envelope>";
            _logg.DebugFormat($"xml入参信息：{soapEnvelope}");
            // 创建HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("SOAPAction", "\"http://tempuri.org/MIHandel\"");
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Accept = "text/xml";
            request.Method = "POST";

            // 将SOAP请求写入请求流
            using (Stream stream = request.GetRequestStream()) {
                byte[] data = Encoding.UTF8.GetBytes(soapEnvelope);
                stream.Write(data, 0, data.Length);
            }

            // 获取并处理响应
            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                string result = reader.ReadToEnd();
                _logg.DebugFormat($"响应信息：{result}");
            }
        }
        public static string SerializeObjectToXml<T>(T obj) {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringWriter writer = new StringWriter()) {
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }
        //判断是否干诊
        public static bool IfPass() {
            Adodb.GetScalar<string>(@"select * from 就诊登记记录 wehere ");
            return true;
        }
    }
   
}
